package com.mall.order.biz.handler;

import com.mall.commons.tool.exception.BizException;
import com.mall.commons.tool.utils.NumberUtils;
import com.mall.order.biz.callback.SendEmailCallback;
import com.mall.order.biz.callback.TransCallback;
import com.mall.order.biz.context.CreateOrderContext;
import com.mall.order.biz.context.TransHandlerContext;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.constants.OrderConstants;
import com.mall.order.dal.entitys.Order;
import com.mall.order.dal.entitys.OrderItem;
import com.mall.order.dal.persistence.OrderItemMapper;
import com.mall.order.dal.persistence.OrderMapper;
import com.mall.order.dto.CartProductDto;
import com.mall.order.utils.GlobalIdGeneratorUtil;
import com.mall.user.IAddressService;
import com.mall.user.dto.AddressDetailRequest;
import com.mall.user.dto.AddressDetailResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 初始化订单 生成订单
 * @author Javid Xi
 * @version 1.0
 * @since 2021/7/20
 */
@Slf4j
@Component
public class InitOrderHandler extends AbstractTransHandler {

    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderItemMapper orderItemMapper;
    @Reference(check = false)
    IAddressService addressService;

    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    public boolean handle(TransHandlerContext context) {
        CreateOrderContext createOrderContext = (CreateOrderContext) context;
        // 生成UUID
        String orderId = UUID.randomUUID().toString().replace("-", "");

        AddressDetailRequest addressRequest = new AddressDetailRequest();
        String nickName = null;
        if(createOrderContext.getAddressId() != null){
            addressRequest.setAddressId(createOrderContext.getAddressId());
            AddressDetailResponse addressDetailResponse = addressService.addressDetail(addressRequest);
            nickName = addressDetailResponse.getAddressDto().getUserName();
        } else {
            nickName = createOrderContext.getBuyerNickName();
        }

        // 插入订单表
        Order order = new Order();
        order.setBuyerNick(nickName);
        order.setOrderId(orderId);
        order.setUserId(createOrderContext.getUserId());
        order.setPayment(createOrderContext.getOrderTotal());
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());
        order.setStatus(OrderConstants.ORDER_STATUS_INIT);
        int affectRows = orderMapper.insert(order);

        if(affectRows != 1){
            throw new BizException(OrderRetCode.DB_SAVE_EXCEPTION.getCode(),
                    OrderRetCode.DB_SAVE_EXCEPTION.getMessage());
        }

        //插入OrderItem表
        List<Long> buyProductIds = new ArrayList<>();

        List<CartProductDto> cartProductDtoList = createOrderContext.getCartProductDtoList();
        for (CartProductDto cartProductDto : cartProductDtoList) {
            OrderItem orderItem = new OrderItem();
            String orderItemId = UUID.randomUUID().toString().replace("-", "");

            orderItem.setId(orderItemId);
            orderItem.setItemId(cartProductDto.getProductId());
            orderItem.setOrderId(orderId);
            orderItem.setNum(cartProductDto.getProductNum().intValue());
            orderItem.setPrice(cartProductDto.getSalePrice().doubleValue());
            orderItem.setTitle(cartProductDto.getProductName());
            orderItem.setPicPath(cartProductDto.getProductImg());

            BigDecimal total = cartProductDto.getSalePrice().multiply(new BigDecimal(cartProductDto.getProductNum()));
            orderItem.setTotalFee(total.doubleValue());
            //库存状态已锁定
            orderItem.setStatus(1);
            buyProductIds.add(cartProductDto.getProductId());

            affectRows = orderItemMapper.insert(orderItem);
            if(affectRows != 1){
                throw new BizException(OrderRetCode.DB_SAVE_EXCEPTION.getCode(),
                        OrderRetCode.DB_SAVE_EXCEPTION.getMessage());
            }
        }

        createOrderContext.setOrderId(orderId);
        createOrderContext.setBuyProductIds(buyProductIds);
        return true;
    }
}
